package com.lfx.concurrent;

public class ReadWriteLock {

    //读取的线程数
    private int readingReaders = 0;

    //等待写入线程数
    private int waitingWriters = 0;

    //正在写入线程数
    private int  writingWriters = 0;

    //是否偏向写
    private boolean preferWriter = true;


    public synchronized void readLock() throws InterruptedException {
        if(waitingWriters>0||(preferWriter&&waitingWriters>0))
            wait();
    }

    public synchronized void readUnlock(){
        readingReaders--;
        preferWriter=true;
        notifyAll();
    }


    public synchronized void writerLock() throws InterruptedException {
        waitingWriters++;
        while (readingReaders>0||writingWriters>0){//存在正在读取线程或者存在写入线程
            wait();
        }
        writingWriters++;
        waitingWriters--;

    }



    public synchronized void writerUnLock(){
        writingWriters--;
        preferWriter=false;
        notifyAll();
    }
}
